package com.example.invoke.controller;

import org.redisson.api.RKeys;
import org.redisson.api.RLock;
import org.redisson.api.RSet;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * redisson相关
 */
@RestController
@RequestMapping("redisson")
public class RedissonController {

    @Autowired
    private RedissonClient redissonClient;

    @GetMapping()
    public String redisson () {
        Config config = redissonClient.getConfig();
        System.out.println(config);
        RKeys keys = redissonClient.getKeys();
        keys.getKeys().forEach(key -> System.out.println(key));
        return "13213";
    }

    @GetMapping(value = "add/{key}")
    public String add (@PathVariable(value = "key") String key) {
        RLock lock = redissonClient.getLock("aa_aa");
        try {
            boolean tryLock = lock.tryLock(50, 100, TimeUnit.SECONDS);
            if (tryLock) {
                RSet<Object> aaa = redissonClient.getSet("aaa");
                Thread.sleep(5000);
                tt();
            } else {
                System.out.println("tryLock: false");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }  finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }

        return "13213";
    }

    private void tt () {
        RLock lock = redissonClient.getLock("aa_aa");
        try {
            boolean tryLock = lock.tryLock(50, 100, TimeUnit.SECONDS);
            if (tryLock) {
                RSet<Object> aaa = redissonClient.getSet("aaa");
                Thread.sleep(5000);
            } else {
                System.out.println("tryLock: false");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }  finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}
